import sys
from socket import *
from multiprocessing import Process
import signal
from sql_Sever import DataBase

IP = "0.0.0.0"
PORT = 9999
ADDR = (IP, PORT)
db = DataBase(database="userlist")


def do_register(c, data):
    tmp = data.split(" ")
    name = tmp[1]
    password = tmp[2]
    if db.register(name, password):
        c.send(b"OK")
    else:
        c.send(b"Fail")

def do_login(c, data):
    tmp = data.split(" ")
    name = tmp[1]
    password =tmp[2]
    if db.login(name, password):
        c.send(b"OK")
    else:
        c.send(b"Fail")

def do_query(c,data):
    tmp = data.split(" ")
    name = tmp[1]
    word = tmp[2]
    mean=db.query(word,name)
    if mean:
        c.send(mean.encode())
    else:
        c.send("没有找到该单词".encode())

def do_history(c,data):
    tmp = data.split(" ")
    name = tmp[1]
    history=db.history(name)
    if history:
        c.send(history.encode())
    else:
        c.send("抱歉您目前没有历史记录".encode())

# 循环接收客户端请求
def resquset(conn):
    db.create_cursor()  # 每个子进程,单独生成游标
    while True:
        data = conn.recv(1024).decode('utf-8')
        if not data or data[0] == "E":
            sys.exit()
        print(conn.getpeername(), ":", data)
        if data[0] == 'R':
            do_register(conn, data)
        elif data[0]=='L':
            do_login(conn,data)
        elif data[0]=='Q':
            do_query(conn,data)
        elif data[0]=='H':
            do_history(conn,data)


def main():
    s = socket(AF_INET, SOCK_STREAM)
    s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    s.bind(ADDR)
    s.listen(5)
    signal.signal(signal.SIGABRT, signal.SIG_IGN)
    while True:
        try:
            print("waiting for connection....")
            conn, addr = s.accept()
            print("Connected by", addr)
        except KeyboardInterrupt:
            s.close()
            db.close()
            sys.exit("服务端退出")
        except Exception as e:
            print(e)
            continue
        P = Process(target=resquset, args=(conn,))
        P.daemon = True
        P.start()


if __name__ == "__main__":
    main()
